# -*- coding: utf-8 -*-
# @Time : 2021/11/5 15:35
# @Author : Orange
# @File : get_big_data_P.py
from .constant_value import *


def get_iv_data(start_time, end_time, equip_id, station_id, equip_mk, downSample):
    l = []
    for i in range(len(equip_id)):
        l.append({
            "aggregator": "avg",
            "downsample": downSample,
            "explicitTags": True,
            "metric": "EMS.P",
            "tags": {
                "equipID": equip_id[i],
                "equipMK": equip_mk[i],
                "staId": station_id
            }
        })

    d = {
        "dataSource": "EMS",
        "endTime": end_time,
        "isClean": False,
        "listQueries": l,
        "startTime": start_time,
        "userKey": BIGDATA_USERKEY
    }

    url = BIGDATA_DOMAIN + '/internal/bigdata/time_series/get_history'
    r = requests.post(url, json=d)
    return r.json()


def P_big_data_process(start_time, end_time, equip_id, station_id, equip_mk, downSample):
    """
    :param data: 从大数据接口获取的原始数据
    :return: 处理好的DataFrame数据结构
    """
    import time
    data = get_iv_data(start_time, end_time, equip_id, station_id, equip_mk, downSample)
    data_org = data['data']
    data = data_org[0].get('dps')
    data = sorted(zip(data.keys(), data.values()))  # 字典无序,按照时间戳排序
    P_data = [i[1] for i in data]  # 取出排气温度值
    time = [time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(i[0]))) for i in data]  # 将时间戳变为时间序列
    P_DATAFRAME = pd.DataFrame(P_data, index=time, columns=["P"])
    for i in range(1, len(data_org)):
        data = data_org[i].get('dps')
        data = sorted(zip(data.keys(), data.values()))  # 字典无序,按照时间戳排序
        P_data = [i[1] for i in data]  # 取出排气温度值
        P_DATAFRAME = pd.DataFrame(P_data, index=time, columns=["P"]) + P_DATAFRAME
    if P_DATAFRAME.empty:  # 该企业无有效数据
        raise ValueError("DataFrame为空，该企业无有效数据")
    return P_DATAFRAME


